var express = require('express');
var port = process.env.PORT || 3000;
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var abPath = path.join(__dirname, 'public');
var Moive = require("./models/moive");
var underscore = require("underscore");

mongoose.connect('mongodb://localhost/imooc');


app.use(express.static(abPath));
app.set('views','./views/pages');
app.set('view engine','jade');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());


app.get('/',function(req, res){

	Moive.fetch(function(err, moives){
		if(err){
			console.log(err);
		}

		res.render('index',{
			pageTitle:"首页",
			moives:moives
		});
	});
});

app.post('/admin/moive/new', function(req, res){
	var id = req.body.moive._id;
	var moiveObj = req.body.moive;

	var _moive;

	if(id){
		Moive.findById(id, function(err, moive){
			if(err){
				console.log(err);
			}

			_moive = underscore.extend(moive, moiveObj);
			_moive.save(function(err, moive){
				if(err){
					console.log(err);
				}
				res.redirect('/moive/'+ moive._id);
			});
		});
	}
	else{
		_moive = new Moive({
			title: moiveObj.title,
			poster: moiveObj.poster,
			flash: moiveObj.flash
		});
		_moive.save(function(err,moive){
			if(err){
					console.log(err);
				}
			res.redirect('/moive/'+ moive._id);
		});
	}
});

app.get('/admin/new',function(req, res){
	res.render('admin', {
		pageTitle:"后台录入页",
		moive:{
			_id:"",
			title:"",
			poster:"",
			flash:""
		}
	});
});

app.get('/admin/update/:id', function(req, res){
	var id = req.params.id;
	if(id){
		Moive.findById(id, function(err, moive){
			if(err){
				console.log(err);
			}
			res.render('detail',{
				pageTitle:"电影详情",
				moive:moive
			});
		});
	}
});

app.get('/admin/list',function(req,res){
	Moive.fetch(function(err, moives){
		res.render('list', {
			pageTitle:"列表",
			moives:moives
		});
	});	
});

app.get('/moive/:id',function(req, res){

	var id = req.params.id;

	Moive.findById(id, function(err, moive){
		if(err){
			console.log(err);
		}
		res.render('detail',{
			pageTitle:"电影详情",
			moive:moive
		});
	});
});



app.listen(port,function(){
	console.log('server start success')	;
});
